//
//  KWNFindMMViewController.m
//  KWNClient
//
//  Created by 张明磊 on 14/10/31.
//  Copyright (c) 2014年 张明磊. All rights reserved.
//

#import "KWLFindMMViewController.h"
#import "KWNNetwork.h"
#import "Model_user.h"
#import "KWNFinishViewController.h"
#import "Model_question.h"

typedef NS_ENUM(NSInteger, KWNFindMMButtonTag){
    KWNFindMMButtonTag_back          = 0,
    KWNFindMMButtonTag_next                ,
    KWNFindMMButtonTag_send               ,
};


@interface KWLFindMMViewController ()<UITextFieldDelegate>

@property (strong, nonatomic) UITextField *textField_phone;
@property (strong, nonatomic) UITextField *textField_number;
@property (strong, nonatomic) UIButton *button_receive;
@property (strong, nonatomic) UIView *imageView_title;
@property (strong, nonatomic) UIImageView *imageview_findtop;
@property (strong, nonatomic) UIView *view_phone;
@property (strong, nonatomic) UIView *view_number;
/*
 递减数
 */
@property (assign, nonatomic) NSInteger time_countDown;

/*
 计时器
 */
@property (assign, nonatomic) NSTimer *timer_countDown;

@end

@implementation KWLFindMMViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    [self UI_findMM];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"FindMMPage"];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"FindMMPage"];
}

- (void)UI_findMM{
    _imageView_title = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44 + IOS7_SIZE)];
    _imageView_title.backgroundColor = RGB(91, 165, 229);
    
    UIButton *button_menu = [UIButton buttonWithType:UIButtonTypeCustom];
    button_menu.frame = CGRectMake(0, IOS7_SIZE, 60, 45);
    [button_menu setImage:[UIImage imageFileName:@"button_back.png"] forState:UIControlStateNormal];
    //button_menu.tag = KWNDetailViewButtonTag_back;
    [button_menu addTarget:self action:@selector(didClickButton_findMM:) forControlEvents:UIControlEventTouchUpInside];
    button_menu.tag = KWNFindMMButtonTag_back;
    
    UIButton *button_login = [UIButton buttonWithType:UIButtonTypeCustom];
    button_login.frame = CGRectMake(250, IOS7_SIZE, 60, 45);
    [button_login setTitle:@"下一步" forState:UIControlStateNormal];
    [button_login setTitleColor:ColorOfTitle forState:UIControlStateNormal];
    button_login.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0f];
    [button_login addTarget:self action:@selector(didClickButton_findMM:) forControlEvents:UIControlEventTouchUpInside];
    button_login.tag = KWNFindMMButtonTag_next;
    
    UILabel *label_title = [[UILabel alloc] initWithFrame:CGRectMake(_imageView_title.frame.origin.x,IOS7_SIZE + 5,_imageView_title.frame.size.width,35)];
    label_title.backgroundColor = [UIColor clearColor];
    label_title.textColor = ColorOfTitle;
    label_title.textAlignment = NSTextAlignmentCenter;
    label_title.font = [UIFont fontWithName:@"Helvetica-Bold" size:16.0f];
    label_title.text = @"验证身份";
    
    _imageview_findtop = [[UIImageView alloc] initWithFrame:CGRectMake((MainScreenWidth - 291)/2, _imageView_title.frame.origin.y + _imageView_title.frame.size.height + (108 - 82)/2, 291, 82)];
    _imageview_findtop.layer.cornerRadius = 2;
    _imageview_findtop.backgroundColor = RGB(247, 247, 247);
//    _imageview_findtop.image = [UIImage imageFileName:@"findmm_top.png"];
    [self.view addSubview:_imageview_findtop];

    UILabel *label_imageview_findtop = [UIUtils creatLabel];
    label_imageview_findtop.textColor = RGB(170, 169, 169);
    label_imageview_findtop.frame = CGRectMake(15, 10, _imageview_findtop.frame.size.width - 25, _imageview_findtop.frame.size.height - 20);
    label_imageview_findtop.numberOfLines = 0;
    label_imageview_findtop.font = FontOfSystem(13);
    label_imageview_findtop.text = @"为了验证您的身份，请填写注册时使用的手机\n号，我们将以短信的方式向这个手机发送验证\n码。";
    [_imageview_findtop addSubview:label_imageview_findtop];

    
    _view_phone = [[UIView alloc] initWithFrame:CGRectMake(10, _imageView_title.frame.origin.y + _imageView_title.frame.size.height + 108, 300, 46)];
    _view_phone.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_view_phone];
    //设置矩形四个圆角半径
    _view_phone.layer.cornerRadius = 5.0;
    _view_phone.layer.borderWidth = 1.0;//边框宽度
    _view_phone.layer.borderColor = RGB(198, 198, 198).CGColor;//边框颜色
    
    _textField_phone = [[UITextField alloc] initWithFrame:CGRectMake(30, _view_phone.frame.origin.y, 260, 46)];
    _textField_phone.backgroundColor = [UIColor clearColor];
    _textField_phone.textColor = [UIColor blackColor];
    _textField_phone.textAlignment = NSTextAlignmentLeft;
    _textField_phone.placeholder = @"请输入手机号";
    _textField_phone.font = [UIFont systemFontOfSize:15];
    _textField_phone.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _textField_phone.clearButtonMode = UITextFieldViewModeAlways;
    _textField_phone.keyboardType = UIKeyboardTypeNumberPad;
    //去掉首字母大写和自动纠错
    _textField_phone.autocorrectionType = UITextAutocorrectionTypeNo;
    _textField_phone.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _textField_phone.delegate = self;
    //字多自动缩进
    _textField_phone.adjustsFontSizeToFitWidth = YES;
    //缩进最小字体
    _textField_phone.minimumFontSize = 20;
    [self.view addSubview:_textField_phone];
//    [textField_phone becomeFirstResponder];
    
    _view_number = [[UIView alloc] initWithFrame:CGRectMake(10, _view_phone.frame.origin.y + _view_phone.frame.size.height + Iphone5_size(20, 5), 300, 46)];
    _view_number.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_view_number];
    //设置矩形四个圆角半径
    _view_number.layer.cornerRadius = 5.0;
    _view_number.layer.borderWidth = 1.0;//边框宽度
    _view_number.layer.borderColor = RGB(198, 198, 198).CGColor;//边框颜色
    
    _textField_number = [[UITextField alloc] initWithFrame:CGRectMake(30, _view_number.frame.origin.y, 260, 46)];
    _textField_number.backgroundColor = [UIColor clearColor];
    _textField_number.textColor = [UIColor blackColor];
    _textField_number.textAlignment = NSTextAlignmentLeft;
    _textField_number.placeholder = @"请输入验证码";
    _textField_number.font = [UIFont systemFontOfSize:15];
    _textField_number.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _textField_number.clearButtonMode = UITextFieldViewModeAlways;
    _textField_number.keyboardType = UIKeyboardTypeNumberPad;
    //去掉首字母大写和自动纠错
    _textField_number.autocorrectionType = UITextAutocorrectionTypeNo;
    _textField_number.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _textField_number.delegate = self;
    //字多自动缩进
    _textField_number.adjustsFontSizeToFitWidth = YES;
    //缩进最小字体
    _textField_number.minimumFontSize = 20;
    [self.view addSubview:_textField_number];
//    [textField_number becomeFirstResponder];
    
    _button_receive = [UIButton buttonWithType:UIButtonTypeCustom];
    _button_receive.frame = CGRectMake(_view_number.frame.origin.x, _view_number.frame.origin.y + _view_number.frame.size.height + Iphone5_size(20, 10), _view_number.frame.size.width, _view_number.frame.size.height);
    _button_receive.backgroundColor = RGB(91, 165, 229);
    [_button_receive setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_button_receive setTitle:@"获取验证码" forState:UIControlStateNormal];
    _button_receive.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0f];
    [_button_receive addTarget:self action:@selector(didClickButton_findMM:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button_receive];
    _button_receive.tag = KWNFindMMButtonTag_send;
    _button_receive.layer.cornerRadius = 5.0;
    
    UIButton *button_closeKey = [UIButton buttonWithType:UIButtonTypeCustom];
    button_closeKey.frame = CGRectMake(0, 0, 320, 30);
    [button_closeKey setImage:[UIImage imageFileName:@"button_closeKey.png"] forState:UIControlStateNormal];
    [button_closeKey addTarget:self action:@selector(clickBtn_findmmCloseKeyBored)forControlEvents:UIControlEventTouchUpInside];
    [_textField_number setInputAccessoryView:button_closeKey];
    [_textField_phone setInputAccessoryView:button_closeKey];
    button_closeKey.tag = 102;

    [self.view addSubview:_imageView_title];
    [self.view addSubview:button_menu];
    [self.view addSubview:button_login];
    [self.view addSubview:label_title];

}

- (void)clickBtn_findmmCloseKeyBored
{
    [self.view endEditing:YES];
}


- (void)didClickButton_findMM:(UIButton *)button{
    switch (button.tag) {
        case KWNFindMMButtonTag_back:{
            [self popViewController];
        }break;
        case KWNFindMMButtonTag_send:{
            if(_textField_phone.text.length == 0){
                [SVProgressHUD showErrorWithStatus:@"请输入电话" duration:1.5];
            }
            else if([UIUtils validateMobile:_textField_phone.text]){
                [SVProgressHUD showWithStatus:@"发送中..." maskType:SVProgressHUDMaskTypeClear];
                [[KWNNetwork sharedInstance]user_findMMPhone:_textField_phone.text FinishBlock:^(NSInteger stateCode, NSMutableArray *result){
                    if(stateCode == 10000){
                        NSString *string_msg  = result[0];
                        [SVProgressHUD dismissWithSuccess:string_msg afterDelay:1.5];
                        [_button_receive setUserInteractionEnabled:NO];
                        [_button_receive setBackgroundColor:RGB(203, 203, 203)];
                        [self startBeginTimeCountDown];
                    }
                    else{
                        NSString *string_msg  = result[0];
                        [SVProgressHUD dismissWithError:string_msg afterDelay:1.5];
                    }
                }];
            }
            else{
                [SVProgressHUD showErrorWithStatus:@"电话号码非法" duration:1.5];
            }
        }break;
        case KWNFindMMButtonTag_next:{
            if(_textField_number.text.length == 0 || _textField_phone.text.length == 0){
                [SVProgressHUD showErrorWithStatus:@"电话号码或验证码为空" duration:1.5];
            }
            else{
                [SVProgressHUD showWithStatus:@"验证中" maskType:SVProgressHUDMaskTypeClear];
                [[KWNNetwork sharedInstance] regist_verifyPhone:_textField_phone.text andCode:_textField_number.text finishBlock:^(NSInteger stateCode, NSMutableArray *result){
                    if(stateCode == 10000){
                        [SVProgressHUD dismiss];
                        NSString *string_uid = result[1];
                        [Model_question sharedInstance].string_phone = _textField_phone.text;
                        [[Model_user sharedInstance] setUID:string_uid];
                        KWNFinishViewController *finish = [[KWNFinishViewController alloc] initWithTag:1];
                        [self pushViewController:finish];
                    }
                    else{
                        NSString *string_msg  = result[0];
                        [SVProgressHUD dismissWithError:string_msg afterDelay:1.5];
                    }
                }];
            }
        }break;
        default:
            break;
    }
}

- (void)findSubViewsFrameUp
{
    [UIView animateWithDuration:0.3 animations:^{
        [_imageview_findtop setFrameTop:_imageview_findtop.frame.origin.y - 40];
        [_view_phone setFrameTop:_view_phone.frame.origin.y - 40];
        [_textField_phone setFrameTop:_textField_phone.frame.origin.y - 40];
        [_view_number setFrameTop:_view_number.frame.origin.y - 40];
        [_textField_number setFrameTop:_textField_number.frame.origin.y - 40];
    }];
}

- (void)findSubViewsFrameRestore
{
    [UIView animateWithDuration:0.3 animations:^{
        [_imageview_findtop setFrameTop:_imageview_findtop.frame.origin.y + 40];
        [_view_phone setFrameTop:_view_phone.frame.origin.y + 40];
        [_textField_phone setFrameTop:_textField_phone.frame.origin.y + 40];
        [_view_number setFrameTop:_view_number.frame.origin.y + 40];
        [_textField_number setFrameTop:_textField_number.frame.origin.y + 40];
    }];
}

#pragma mark - 开始计时 -
/**
 开始计时
 **/
- (void)startBeginTimeCountDown{
    _time_countDown = 60;
    NSTimer *timer_count = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(runTimePage) userInfo:nil repeats:YES];
    _timer_countDown = timer_count;
}

/**
 开始发送读秒
 **/
#pragma mark - 开始发送读秒 -
- (void)runTimePage
{
    _time_countDown --;
    NSString *string_countDown = [NSString stringWithFormat:@"%ld秒内查收",(long)_time_countDown];
    [_button_receive setTitle:string_countDown forState:UIControlStateNormal];
    if(_time_countDown == 0){
        [self stopTimePage];
    }
}

#pragma mark - 停止计时器 -
/**
 停止计时器
 **/
- (void)stopTimePage
{
    [_button_receive setUserInteractionEnabled:YES];
    _button_receive.backgroundColor = RGB(55, 188, 153);
    [_button_receive setTitle:@"重新发送" forState:UIControlStateNormal];
    //[_label_recive setTextColor:[UIColor blackColor]];
    if(_timer_countDown)
    {
        [_timer_countDown invalidate];
        _timer_countDown = nil;
    }
}

#pragma mark - 输入回调 -
/**
 *  输入回调
 */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == _textField_number) {
        
        NSString *device = [UIUtils currentDevicePlatformString];
        if ([device isEqualToString:@"iPhone 4S"]||[device isEqualToString:@"iPhone 4"]||[device isEqualToString:@"Verizon iPhone 4"]) {
            if (_imageview_findtop.frame.origin.y >= _imageView_title.frame.origin.y + _imageView_title.frame.size.height + (108 - 82)/2) {
                [self findSubViewsFrameUp];
            }
        }
    }
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSString *device = [UIUtils currentDevicePlatformString];
    if ([device isEqualToString:@"iPhone 4S"]||[device isEqualToString:@"iPhone 4"]||[device isEqualToString:@"Verizon iPhone 4"]) {
        if (_imageview_findtop.frame.origin.y < _imageView_title.frame.origin.y + _imageView_title.frame.size.height + (108 - 82)/2) {
            [self findSubViewsFrameRestore];
        }
    }
    
}


@end
